package samples.d3.image 
{
	import com.bit101.components.CheckBox;
	import com.bit101.components.HUISlider;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import graphics.raster.Bresenham;
	import samples.BaseSample;
	import utils.GeomUtils;
	
	/**
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Histogram extends BaseSample
	{
		
		[Embed(source = '../../../../lib/lemur1.jpg')]private var imageSrc:Class;
		private var image:Bitmap;
		
		
		private var bd:BitmapData;
		private var bmp:Bitmap;
		
		
		public function Histogram() 
		{
			
			image = new imageSrc();
			var w:int = image.width;
			var h:int = image.height;
			
			
			bd = new BitmapData( w * 2, h * 2, false, 0 );
			bmp = new Bitmap( bd );
			addChild( bmp );
			
			Bresenham.bitmapData = bd;
			
			reset( image.bitmapData );
			
			addChild( image );
			center();
			
		}
		private function reset( src:BitmapData ):void
		{
			bd.fillRect( bd.rect, 0 );
			var w:int = src.width;
			var h:int = src.height;
			
			var vectors:Vector.<Vector.<Number>> = src.histogram( src.rect );
			var i:int = 0;
			var margin:int = 25;
			var pts:Vector.<Point> = Vector.<Point>( [ new Point( w + margin, margin ), new Point( margin, h+margin ),  new Point( w+margin, h+margin ), new Point( 0, 0 ) ] );
			var colors:Vector.<uint> = Vector.<uint>( [ 0xFF0000, 0x00FF00, 0x0000FF, 0 ] );
			
			for each( var vec:Vector.<Number> in vectors )
			{
				drawVector( vec, bd, pts[ i ], colors[ i ] );
				Bresenham.drawRect( new Rectangle( pts[ i ].x, pts[ i ].y, 255, 255 ), 0xFF << 24 | colors[ i ] );
				i++;
			}
		}
			
		private function drawVector( v:Vector.<Number>, bd:BitmapData, dest:Point, col:uint ):void
		{
			
			var x:int = 0;
			var max:int = 0;
			var i:int = 0;
			var n:int = 0;
			
			for ( i = 0; i < v.length - 1; i++ )
			{
				n = v[ i ];
				if ( n > max ) max = n; 
			}
			
			var p:Point = new Point( dest.x, dest.y +  0xFF - GeomUtils.map( n, 0, max, 0, 0xFF ) ), np:Point = new Point();
			for ( i = 0; i < v.length - 1; i++ )
			{
				n = v[ i ];
				x++;
				np.x = dest.x + x;
				np.y = dest.y + 0xFF - GeomUtils.map( n, 0, max, 0, 0xFF );
				Bresenham.drawLine( p.x, p.y, np.x, np.y, 0xFF << 24 | col );
				p = np.clone();
			}
			
			
		}
		
		
	}

}